package com.andfo.testframework;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Will read asynchronously from input/output
 */
public class AsyncStreamReader extends Thread {
     private StringBuffer fBuffer = null;
        private InputStream fInputStream = null;
        private String fThreadId = null;
        private boolean fStop = false;

        private String fNewLine = null;

        static AsyncStreamReader cmdOutputThread;

        public static void startReader(InputStream processOut, String threadName) {
            cmdOutputThread = new AsyncStreamReader(processOut, new StringBuffer(), threadName);
            cmdOutputThread.start();
        }


        public AsyncStreamReader(InputStream inputStream, StringBuffer buffer, String threadId) {
            fInputStream = inputStream;
            fBuffer = buffer;
            fThreadId = threadId;

            fNewLine = System.getProperty("line.separator");
        }

        public String getBuffer() {
            return fBuffer.toString();
        }

        public void run() {
            try {
                readCommandOutput();
            } catch (Exception ex) {
                //ex.printStackTrace(); //DEBUG
            }
        }

        private void readCommandOutput() throws IOException {
            BufferedReader bufOut = new BufferedReader(new InputStreamReader(fInputStream));
            String line = null;
            while ((fStop == false) && ((line = bufOut.readLine()) != null)) {
                fBuffer.append(line + fNewLine);
                printToDisplayDevice(line);
            }
            bufOut.close();
            //printToConsole("END OF: " + fThreadId); //DEBUG
        }

        public void stopReading() {
            fStop = true;
        }

        private void printToDisplayDevice(String line) {
            printToConsole(line);
        }

        private synchronized void printToConsole(String line) {
            System.out.println(line);
        }
}
